#################################################################################
### Title: Are People Willing to Trade Away Democracy for Desirable Outcomes? ###
### Authors: Jonathan A. Chu, Scott Williamson, Eddy S. F. Yeung              ###
### Content: Ranking of attribute-levels analysis                             ###
### Date: September 20, 2025                                                  ###
#################################################################################

### Set-up
## Clean the working environment and set the working directory
rm(list = ls())
setwd("~/Desktop/democracy_tradeoff/replication") # change to your own working directory

## Load the required packages ----
library(cjRank) # if your device doesn't have this package, run "install_github(repo = "carl-mc/cjRank")"
library(tidyverse)

## Read the cleaned and recoded datasets
df_US <- read.csv("df_US.csv")
df_JP <- read.csv("df_JP.csv")
df_EG <- read.csv("df_EG.csv")
df_IN <- read.csv("df_IN.csv")
df_IT <- read.csv("df_IT.csv")
df_TH <- read.csv("df_TH.csv")

## Merge the datasets
df_cj <- bind_rows(df_US, df_JP, df_EG, df_IN, df_IT, df_TH)

### Define objects with variable names ----
## Categorical attribute variables
attr.vars <- c("Leader.Selection", "Civil.Liberties", "Leader.Constraints", 
               "Corruption.in.Politics", "National.Economy", "Respondent.Wealth",
               "Public.Safety", "Health.Care", "Minority.Treatment", "Respondent.Identity")

## Binary outcome variable
outcome <- "selected"

## Unique respondent ID
respid <- "id"

## Unique task x respondent ID
df_cj$resp_pair <- paste0(df_cj$id, ".", df_cj$task)
taskid <- "resp_pair"

### Setting up a cjRank object ----
df_rank <- cjRank$new(data = df_cj, 
                      outcome.var = outcome,
                      task_id.var = taskid,
                      attr_cat.var = attr.vars,
                      resp_id.var = respid,
                      min_obs = 100,
                      cluster_var = respid)

### Derive order and ranking of attribute features ----
order <- df_rank$get_order()
df_rank$feature_key[order]
df_rank$get_ranks()

### Bootstrap the ordering (Table S1) ----
set.seed(1234567)
sum.boot <- df_rank$get_ranks_bs(iter = 100) # this task will take some time
sum.boot <- sum.boot[order(sum.boot$rank, sum.boot$mean),]
sum.boot
